package dao

import (
	"errors"
	"go.uber.org/zap"
	"order_srv/model"
	"order_srv/order"
	"smart-health-platforms/pkg"
)

func CreateAfterSale(in *order.CreateAfterSaleRequest) (*model.AfterSale, error) {
	var orders model.Order
	err := orders.GetByOrderId(int(in.OrderId))
	if err != nil {
		pkg.Error("获取订单信息失败", zap.Error(err))
		return nil, errors.New("获取订单信息失败")
	}
	if orders.Id == 0 {
		pkg.Error("订单不存在", zap.Error(err))
		return nil, errors.New("订单不存在")
	}
	if orders.PayStatus != 2 || orders.Status != 1 && orders.Status != 2 && orders.Status != 3 {
		pkg.Error("该订单不能售后", zap.Error(err))
		return nil, errors.New("该订单不能售后")
	}
	if orders.UserId != uint32(in.UserId) {
		pkg.Error("无权操作他人订单", zap.Error(err))
		return nil, errors.New("无权操作他人订单")
	}

	afterSale := &model.AfterSale{
		OrderId:      uint(orders.Id),
		UserId:       uint(orders.UserId),
		Type:         uint(in.Type),
		Reason:       in.Reason,
		RefundAmount: orders.TotalPrice,
		Images:       in.Images,
	}

	err = afterSale.CreateSale()
	if err != nil {
		pkg.Error("创建售后失败", zap.Error(err))
		return nil, errors.New("创建售后失败")
	}
	return afterSale, nil

}

func GetAfterSale(in *order.GetAfterSaleRequest) (*model.AfterSale, error) {
	var afterSale model.AfterSale
	err := afterSale.GetSale(int(in.AfterSaleId))
	if err != nil {
		pkg.Error("获取售后信息失败", zap.Error(err))
		return nil, errors.New("获取售后信息失败")
	}
	if afterSale.Id == 0 {
		pkg.Error("售后不存在", zap.Error(err))
		return nil, errors.New("售后不存在")
	}
	return &afterSale, nil
}
